<template>
    <ComECharts :option="option"/>
</template>
  
<script lang="ts" setup name="Dynamic">
// 引入echarts组件
import ComECharts from '@/components/ComEcharts/index.vue'
import { onMounted, ref,onBeforeUnmount ,nextTick} from "vue";
import moment from 'moment'

// 模拟随机初始数据
let xData = ref([])
let yData = ref([])
let option=ref()
option.value =
{
    animation:false,
    legend: {},
    xAxis: {
        boundaryGap: false,//x轴顶头
        axisLabel: {
            formatter: function (value: any) {
                return moment(value * 1).format("HH:mm:ss"); // 格式化时间为时:分:秒
            }
        },
        data: xData,
    },
    yAxis: {},
    series: [
        {
            name: "用户量",
            type: "line",
            data: yData
        }
    ]
}
//模板都渲染完成后
onMounted(()=>{
    //模拟初始数据
    for (let index = 1; index < 200; index++) {
    xData.value.unshift(moment().subtract(index, "seconds").valueOf() as never)
    yData.value.unshift(Math.floor(Math.random() * 101) as never)}
})

//模拟每秒的异步请求，并修改option
const timer = setInterval(function () {
    //这里同步更改只会触发一次侦听器
    xData.value.push(Date.now() as never)
    yData.value.push(Math.floor(Math.random() * 101) as never)
    if (xData.value.length > 200) { //限制数据长度为一千秒
        xData.value.shift();
        yData.value.shift();
    }
}, 1000);

//清除定时器
onBeforeUnmount(() => {
    clearInterval(timer)
})


</script>